package addition;

/**
 * 3、给定一个数组int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79},
 * 使用二分查找法（binarySearch方法）在数组中查找关键字59，并输出查找结果；
 */
public class Q3 {

    /**
     * 二分法检索
     *
     * @param arr    数组
     * @param target 目标数
     * @return 下标
     */
    public static int binarySearch(int[] arr, int target) {
        int low = 0, high = arr.length - 1, mid;

        while (low <= high) {
            mid = (low + high) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] > target) {
                high = mid - 1;
            } else if (arr[mid] < target) {
                low = mid + 1;
            }
        }

        return -1;
    }

}
